<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/27
 * Time: 15:34
 */

namespace App\Http\Controllers\Admin;
use App\Model\Address;
use App\Model\GoodsSpecsName;
use App\Model\GoodsSpecsVal;
use App\Model\Members;
use App\Model\Branch;
use App\Model\PurchaseOrder;
use App\Model\Replenish;
use App\Model\ShopOrder;
use App\Model\ShopOrderComment;
use App\Model\StoresCenter;
use App\Model\ShopGoods;
use App\Model\StoresCenterGoods;
use App\Model\StoreGoodsSet;
use App\Model\ShopGoodsClassify;
use App\Model\StoresProfitRecord;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Excel;
use Auth;
class StoresCenterController extends BaseController
{
    /**
     * 门店中心
     */
    public function CenterIndex() {
        return view('Admin.stores.stores');
    }


    /**
     * 门店收益
     */
    public function StoreRecord() {
        return view('Admin.stores.record');
    }


    /**
     * 门店订单
     */
    public function StoreOrder() {
        return view('Admin.stores.order');
    }


    /**
     * 库存更改记录
     */
    public function InventoryRecord() {
        return view('Admin.stores.inventory');
    }

    /**
     * 进货记录
     */
    public function purchase()
    {
        return view('Admin.stores.purchase');
    }

    public function getPurchase( Request $request )
    {
        $data = $request->all();
        switch ( $data['class'] ){
            case 'select'://查询订单
                //关键字
                $keyword = empty($data['keyword'])?0:$data['keyword'];
                $order = PurchaseOrder::where('status','!=',0)
                    ->orderBy('paytime','desc')
                    ->where(function($query) use($keyword) {//支付时间
                        if (!empty( $keyword['createtime'][0]) && !empty( $keyword['createtime'][1] ) ) {
                            $query->where('paytime', '>=', $keyword['createtime'][0] )
                                ->where('paytime', '<=', $keyword['createtime'][1] );
                        }
                    })
                    ->where( function( $query ) use( $keyword ) {//关键字
                        if ( !empty( $keyword['keyword'] ) ) {
                            $query->where('stores_name', 'like', '%' . $keyword['keyword'] . '%' )
                                ->orWhere( 'stores_num', $keyword['keyword'] )
                                ->orWhere( 'ordersn',$keyword['keyword']);
                        }
                    })
                    ->where( function( $query ) use ( $keyword ) {//订单状态
                        if ( !empty( $keyword['status'] ) ){
                            $query->where('status',$keyword['status']);
                        }
                    })
                    ->paginate(15);
                foreach ( $order as $key => $value ){
                    $order[$key]['total'] = $value['total_price'] + $value['postage'];
                }
                if ( $order ){
                    return ['code' => 1 ,'data' => $order];
                } else {
                    return ['code' => 0 ,'data' => '暂无数据'];
                }
                break;
            case 'specs'://查看订单商品规格
                $order = PurchaseOrder::where(['id' => $data['id']])->first();
                $data = [
                    'goods_name' => $order['goods_name'],
                    'specs' => $order['specs_txt'],
                    'price' => $order['price'],
                    'total_quantity' => $order['total_quantity'],
                    'paytime' => $order['paytime']
                ];
                if ( $order ){
                    return ['code' => 1,'data' => $data];
                } else {
                    return ['code' => 0,'data'=> '商品无规格'];
                }
                break;
            case 'confirm'://确认发货
                $order = PurchaseOrder::where(['id' => $data['id']])->first();
                $order->express_time = date('Y-m-d H:i:s',time());
                $order->status = 2;
                $re = $order->save();
                $goods = ShopGoods::where(['goodsname' => $order['goods_name']])->first();
                $goods->total = $goods->total - $order['resale'] - $order['invoices'];
                $res  = $goods->save();
                if ( $res && $re ){
                    return ['code' => 1 ,'data' => '发货成功'];
                } else {
                    return ['code' => 0 ,'data' => '发货失败'];
                }
                break;
        }

    }

    /**
     * 补货记录
     */
    public function replenish()
    {
        return view('Admin.stores.replenish');
    }

    public function getReplenish( Request $request )
    {
        $data = $request->all();
        switch ( $data['class'] ){
            case 'select'://查询订单
                //关键字
                $keyword = empty($data['keyword'])?0:$data['keyword'];
                $order = Replenish::where('status','!=',0)
                    ->orderBy('paytime','desc')
                    ->where(function($query) use($keyword) {//支付时间
                        if (!empty( $keyword['createtime'][0]) && !empty( $keyword['createtime'][1] ) ) {
                            $query->where('paytime', '>=', $keyword['createtime'][0] )
                                ->where('paytime', '<=', $keyword['createtime'][1] );
                        }
                    })
                    ->where( function( $query ) use( $keyword ) {//关键字
                        if ( !empty( $keyword['keyword'] ) ) {
                            $query->where('stores_name', 'like', '%' . $keyword['keyword'] . '%' )
                                ->orWhere( 'stores_num', $keyword['keyword'] )
                                ->orWhere( 'ordersn',$keyword['keyword']);
                        }
                    })
                    ->where( function( $query ) use ( $keyword ) {//订单状态
                        if ( !empty( $keyword['status'] ) ){
                            $query->where('status',$keyword['status']);
                        }
                    })
                    ->paginate(15);
                if ( $order ){
                    return ['code' => 1 ,'data' => $order];
                } else {
                    return ['code' => 0 ,'data' => '暂无数据'];
                }
                break;
            case 'specs'://查看订单商品规格
                $order = Replenish::where(['id' => $data['id']])->first();
                $data = [
                    'goods_name' => $order['goods_name'],
                    'resale_specs' => $order['resale_specs'],
                    'resale' => $order['resale'],
                    'invoices_specs' => $order['invoices_specs'],
                    'invoices' => $order['invoices'],
                    'postage' => $order['postage'],
                    'paytime' => $order['paytime']
                ];
                if ( $order ){
                    return ['code' => 1,'data' => $data];
                } else {
                    return ['code' => 0,'data'=> '商品无规格'];
                }
                break;
            case 'confirm'://确认发货
                $stores_num = $data['stores_num'];
                $uid = StoresCenter::where('number',$stores_num)->value('uid');
                $user = Members::where(['uid' => $uid])->first();//获取账号信息
                $order = Replenish::where(['id' => $data['id']])->first();
                 //获取门店信息
                DB::beginTransaction();
                $store = StoresCenter::where(['uid' => $uid])->first();
                $order->express_time = date('Y-m-d H:i:s',time());
                $order->status = 2;
                $re = $order->save();
                if ( !$re ) {
                    return ['code' => 0,'data' => '发货失败'];
                }
                //查询商品库存并增加
                $goods = StoresCenterGoods::where(['goodsname' => $order['goods_name'],'stores_sn' => $stores_num])->first();
                $storeGoodsData = StoresCenterGoods::where('stores_sn', $stores_num)->get()->toArray();
                $inventoryBefore = $goods['inventory'];
                if (is_null($goods['specs_txt'])){
                    $inventoryAfter = $goods['inventory'] + $order['resale'] + $order['invoices'];
                    $goods['inventory'] = $inventoryAfter;
                } else {
                    $specs = explode('|',$goods['specs_txt']);//库存改为数组形式
                    foreach ( $specs as $key => $value ) {
                        $str = substr($value, 0, strrpos($value, "--"));
                        $str = substr($str, 1, -1);
                        $specs[$key] = array_filter(explode(';', $str));
                        foreach ( $specs[$key] as $kk => $vv ){
                            $array[$key]['specs'][] =  substr($vv,strripos($vv,":")+1);
                        }
                        $array[$key]['revise'] = 0;
                        //数量
                        $str2 = strstr($value,'--');
                        $number = substr($str2,2);
                        $array[$key]['number'] = $number;
                        $specs[$key] = $array[$key];
                    }

                    $resaleSpecs = array();//进货规格改为数组形式
                    $orderSpecs = explode(';',$order['resale_specs']);
                    foreach ($orderSpecs as $value){
                        if ($value != ''){
                            $resaleSpecs[] = $value;
                        }
                    }
                    $newArr = array();
                    foreach ($resaleSpecs as $key => $value){
                        $str = substr($value,0,strrpos($value, "-"));
                        $list = explode('-',$str);
                        $newArr[$key]['specs'] =  $list;
                        //数量
                        preg_match_all("/\d+/",$value,$arr);
                        $newArr[$key]['number'] = $arr[0][0];
                    }

                    $resaleSpecs = $newArr;
                    $invoicesSpecs = array();//报单补货规格改为数组形式
                    $orderSpecs = explode(';',$order['invoices_specs']);
                    foreach ($orderSpecs as $value){
                        if ($value != ''){
                            $invoicesSpecs[] = $value;
                        }
                    }
                    $newArr = array();
                    foreach ($invoicesSpecs as $key => $value){
                        $str = substr($value,0,strrpos($value, "-"));
                        $list = explode('-',$str);
                        $newArr[$key]['specs'] =  $list;
                        //数量
                        preg_match_all("/\d+/",$value,$arr);
                        $newArr[$key]['number'] = $arr[0][0];
                    }
                    $invoicesSpecs = $newArr;
                    //修改商品规格库存

                    foreach ( $specs as $k => $v ){
                        foreach ( $resaleSpecs as $kk => $vv ){
                            $result = array_diff($v['specs'],$vv['specs']);
                            if ( empty($result) ){
                                $specs[$k]['number'] += $vv['number'];
                            }
                        }
                    }
                    foreach ( $specs as $k => $v ){
                        foreach ( $invoicesSpecs as $kk => $vv ){
                            $result = array_diff($v['specs'],$vv['specs']);
                            if ( empty($result) ){
                                $specs[$k]['number'] += $vv['number'];
                            }
                        }
                    }
                    //查询商品规格名
                    $specsName = GoodsSpecsName::where('goods_id',$goods['gid'])->get()->toArray();
                    //将商品规格数组还原为字符串形式
                    foreach ( $specs as $k => $v ){
                        $specsList = '';
                        for ( $i = 0;$i < count($v['specs']);$i++ ){
                            $specsList .= $specsName[$i]['name'].':'.$v['specs'][$i].';';
                        }
                        $specs[$k] = "[".$specsList."]--".$v['number'];
                    }
                    $goods->specs_txt = implode('|',$specs);
                    $inventoryAfter = $goods['inventory'] = $goods['inventory'] + $order['resale'] + $order['invoices'];
                }
                //增加库存修改记录
                if ( $inventoryBefore != $inventoryAfter ){

                    $storeGoodsDataSet['store_number'] = $stores_num;
                    $storeGoodsDataSet['store_name'] = $store['shop_name'];
                    $storeGoodsDataSet['goods_name'] = $order['goods_name'];
                    $storeGoodsDataSet['goods_before'] = is_null($inventoryBefore)? 0:$inventoryBefore;
                    $storeGoodsDataSet['goods_after'] = $inventoryAfter;
                    $storeGoodsDataSet['resale_specs'] = $order['resale_specs'];
                    $storeGoodsDataSet['invoices_specs'] = $order['invoices_specs'];
                    $storeGoodsDataSet['remark'] = '补货了'.$order['goods_name'].',其中复销'.$order['resale'].'件,报单'.$order['invoices'].'件';
                    $storeGoodsDataSet['operator'] = '系统自动';
                    $storeGoodsDataSet['addtime'] = time();
                    $storeGoodsSet = StoreGoodsSet::create($storeGoodsData);
                    if ( !$storeGoodsSet ){
                        DB::rollback();
                        return ['code' => 0,'data' => '发货失败'];
                    }
                }
                $goodsInventory = ShopGoods::where(['goodsname' => $order['goods_name']])->first();
                $goodsInventory->total = $goodsInventory->total-$order['total_quantity'];
                $inventory = StoresCenterGoods::where(['goodsname' => $order['goods_name'],'stores_sn' => $stores_num])->value('inventory');
                if ($inventory != $inventoryBefore ){
                    DB::rollback();
                    return ['code' => 0,'data' => '系统繁忙,请稍后再试'];
                }
                $count = StoresCenterGoods::where(['goodsname' => $order['goods_name'],'stores_sn' => $stores_num])->count();
                if ($count < 1){
                    $storeGoods = [
                        'gid' => ShopGoods::where('goodsname',$order['goods_name'])->value('id'),
                        'stores_id' => $store['id'],
                        'stores_sn' => $stores_num,
                        'goodsname' => $order['goods_name'],
                        'inventory' => $inventoryAfter,
                        'sold' => 0,
                        'time' => time(),
                        'updated_at' => date('Y-m-d H:i:s',time())
                    ];
                    if (isset($goods['specs_txt'])){
                        $storeGoods['specs_txt'] = $goods['specs_txt'];
                    }
                    $res = StoresCenterGoods::create($storeGoods);
                } else {
                    $res  = $goods->save();
                }

                if (!$res) {
                    DB::rollback();
                    return ['code' => 0,'data' => '发货失败'];
                }
                DB::commit();
                return ['code' => 1,'data' => '已确认发货'];
                break;
        }
    }



    public function Stores(Request $request)
    {
        $data = $request->all();
        $data['keyword'] = empty($data['keyword'])?"":$data['keyword'];
        $StoresCenterModel = new StoresCenter();
        $StoresProfitRecordModel = new StoresProfitRecord();
        $orderModel = new ShopOrder;
        $BranchModel = new Branch();
        $user = session('admin_user');
        switch ($data['class']){
            case 'select': //查询
//                $table = ShopGoodsClassify::where(['type'=>2])->select('id');
//                $classify = $table->get()->toArray();
//                $pid = [];
//                if (!empty($classify)) {
//                    foreach ($classify as $value) {
//                        $pid[] = $value['id'];
//                    }
//                } else {
//                    return ['code'=>0,'data'=>'暂时还没有商品'];
//                }
                $rico = $StoresCenterModel->get_store($data['keyword']);
                $rico = $rico['order'];
                //商品表
                $GoodsModel = new ShopGoods();
                $goods = $GoodsModel->where([ 'type' => 1,'status' =>1])->where('cid','!=',7)->select('id','goodsname','rulingprice')->get();
                foreach ($goods as $k => $v) {
                    $goods[$k]['number'] = 0;
                    $specsName = GoodsSpecsName::where('goods_id',$v['id'])->select('id','name')->get()->toArray();
                    if ( $specsName ){
                        $num = count($specsName);
                        foreach ( $specsName as $key => $value ){
                            $value = GoodsSpecsVal::where('specs_id',$value['id'])->pluck('val')->toArray();
                            $specsData = getCombinationToString($value,$num);
                        }
                        foreach ( $specsData as $kk => $vv){
                            $specsData[$kk] = array();
                            $specsData[$kk]['specs'] = $vv;
                            $specsData[$kk]['number'] = 0;
                        }
                        $goods[$k]['specs'] = $specsData;
                    }
                }
//            var_dump($goods);exit;
                if ($rico) {
                    return ['code'=>1,'data'=>$rico,'goods' => $goods];
                } else {
                    return ['code'=>0,'data'=>'没有数据'];
                }
                break;


            case 'select_store_order': //订单列表
                $data = $request->all();
                $data['keyword'] = empty($data['keyword'])?"":$data['keyword'];
                $Members = new Members();
                if(!empty($data['keyword']['keyword'])){
                    $userData = $Members->where('phone','like','%'.$data['keyword']['keyword'].'%')->orWhere('user_name','like','%'.$data['keyword']['keyword'].'%')->select('uid')->get();
                    $uid = [];
                    if ($userData) {
                        foreach ($userData as $k => $v) {
                            $uid[] = $v['uid'];
                        }
                    }
                    $data['keyword']['uid'] = $uid;
                }
                $rico = $orderModel->get_order($data['keyword'],1,1);
                $total = $rico['total'];
                $rico = $rico['order'];
                foreach ($rico as $k => $value) {
                    $rico[$k]->createtime = date('Y-m-d H:i:s', $value->createtime);
                    $rico[$k]->paytime = date('Y-m-d H:i:s',$value->paytime);
                    $rico[$k]->couriertime = date('Y-m-d H:i:s',$value->couriertime);
                    $rico[$k]->stores_number =  $rico[$k]->stores_number=='0'?'未绑定消费门店':$rico[$k]->stores_number;
                    $rico[$k]->stores_name = StoresCenter::where( ['number'=>  $rico[$k]->stores_number ] )->value("shop_name");
                    $rico[$k]->stores_name =  $rico[$k]->stores_name ==''?'':$rico[$k]->stores_name;
                    if($value['addressid']){
                       //$res = Address::where('id',$value['addressid'])->first();
                       //$rico[$k]->addres = $res['province'].$res['city'].$res['district'].$res['address'];
                       //$rico[$k]->name = $res['name'];
                       //$rico[$k]->phone = $res['phone'];

                       //$rico[$k]->addres = $rico[$k]->addres == ''?$rico[$k]->receipt_adr:$rico[$k]->addres;
                       //$rico[$k]->name = $rico[$k]->name == ''?$rico[$k]->receipt_name:$rico[$k]->name;
                       //$rico[$k]->phone = $rico[$k]->phone == ''?$rico[$k]->receipt_phone:$rico[$k]->phone;

                       $rico[$k]->addres = $rico[$k]->receipt_adr;
                       $rico[$k]->name = $rico[$k]->receipt_name;
                       $rico[$k]->phone = $rico[$k]->receipt_phone;

                    }
                    if($value['uid']){
                        $users = $Members->where(['uid' => $value['uid']])->select('user_name','phone')->first();
                        $rico[$k]->user_name = empty($users['user_name'])?$users['phone']:$users['user_name'];
                        $rico[$k]->user_phone = $users['phone'];
                    }
                    if($value['company_id']){
                        $branch = $BranchModel->where(['id' => $value['company_id']])->select('name')->first();
                        $rico[$k]->branch_name = $branch['name'];
                    }
                }
                if ($rico) {
                    return ['code' => 1, 'data' => $rico,'total' => $total];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;
            case 'set':
                $stores_id = $data['id'];
                $stores_sn = STORES_NUMBER( $data['number'] , $stores_id );
                DB::beginTransaction(); //开启事务
                $StoresCenterGoodsModel = new StoresCenterGoods();
                $Goods = $StoresCenterGoodsModel->where(['stores_id' => $stores_id])->count();
                if($Goods == 0){
                    $Stores = array();
                    $storeTotal = 0;
                    foreach ($data['goods'] as $k=>$v) {
                        $Stores[$k]['gid'] = $v['id'];
                        $Stores[$k]['stores_id'] = $stores_id;
                        $Stores[$k]['stores_sn'] = $stores_sn;
                        $Stores[$k]['goodsname'] = $v['goodsname'];
                        $Stores[$k]['inventory'] = $v['number'];
                        $Stores[$k]['time'] = time();
                        $Stores[$k]['specs_txt'] = null;
                        if ( isset($v['specs'])){
                            $specsTxt = '';
                            $number = 0;
                            $specsName = GoodsSpecsName::where('goods_id',$v['id'])->get()->toArray();
                            foreach ( $v['specs'] as $key => $value ){
                                $v['specs'][$key]['specs'] = explode('_',$value['specs']);
                                $number += $value['number'];
                                $specsList = '';
                                for ($i = 0;$i<count($specsName);$i++){
                                    $specsList .= $specsName[$i]['name'].':'.$v['specs'][$key]['specs'][$i].';';
                                }
                                $specs[$k][] ='['.$specsList.']--'.$value['number'];
                                $specsTxt = implode('|',$specs[$k]);
                            }
                    $Stores[$k]['inventory'] = $number;
                    $Stores[$k]['specs_txt'] = $specsTxt;
                }
                //商品单价
                $price = ShopGoods::where('id',$v['id'])->value('memberprice');
                $priceTotal = $v['number'] * $price;
                //门店库存总价
                $storeTotal += $priceTotal;
            }
            if ( $storeTotal > $data['earnest_money']){
                return ['code' => 0,'data' => '商品库存不能大于门店订金'];
            }
                    $rico = $StoresCenterGoodsModel->insert($Stores);
                    if(empty($rico)){
                        DB::rollback();  //回滚
                        return ['code' => 0, 'data' => '失败'];
                    }
                }
                $storesData = [
                    'number'        => $stores_sn,
                    'audit_time'    => time(),
                    'earnest_money' => $data['earnest_money'],
                    'type'          => 1,
                ];
                $StoresCenter = $StoresCenterModel->where(['id' => $stores_id])->update($storesData);
                if(empty($StoresCenter)){
                    DB::rollback();  //回滚
                    return ['code' => 0, 'data' => '失败'];
                } else {
                    DB::commit();  //提交
                    return ['code' => 1, 'data' => $stores_sn];
                }
                break;
            case 'modify': //修改
                $stores_id = $data['id'];
                $rico = $StoresCenterModel->where(['id' => $stores_id])->update(['type' => $data['type']]);
                if($rico){
                    return ['code' => 1, 'data' => '设置成功'];
                } else {
                    return ['code' => 0, 'data' => '设置失败'];
                }
                break;

            case 'see_inventory': //查看门店库存
                $stores_id = $data['id'];
                $StoresCenterGoodsModel = new StoresCenterGoods();
                $GoodsModel = new ShopGoods();
                $storeGoodsId = [];
                $storeGoodsAllId = [];
                $StoresNumber = $StoresCenterModel->where( [ 'id' => $stores_id ] )->value( 'number' );
                $storeGoodsData = StoresCenterGoods::where( [ 'stores_id' => $stores_id ] )->select( 'gid' )->get()->toArray();
                foreach ($storeGoodsData as $key => $value) {
                    array_push( $storeGoodsId, $value['gid'] );
                }

                $table = ShopGoodsClassify::where(['type'=>2])->select('id');
                $classify = $table->get()->toArray();
                $pid = [];
                if (!empty($classify)) {
                    foreach ($classify as $value) {
                        $pid[] = $value['id'];
                    }
                } else {
                    return ['code'=>0,'data'=>'暂时还没有商品'];
                }
                $goods = $GoodsModel->where( [ 'type' => 1, 'status' =>1 ] )
                    ->where('number','!=','00006')
                    ->where('number','!=','00008')
                    ->whereIn( 'cid', $pid )->select( 'id', 'goodsname' )->get()->toArray();
                foreach ($goods as $k => $v) {
                    array_push( $storeGoodsAllId, [ 'gid' => $v['id'], 'goodsname' => $v['goodsname'] ] );
                }
                foreach ($storeGoodsAllId as $k => $v) {
                    $goodsIdExist = in_array( $v['gid'], $storeGoodsId );
                    if ( !$goodsIdExist ) {
                        $goodsDatas['gid'] = $v['gid'];
                        $goodsDatas['stores_id'] = $stores_id;
                        $goodsDatas['stores_sn'] = $StoresNumber;
                        $goodsDatas['goodsname'] = $v['goodsname'];
                        $goodsDatas['inventory'] = 0;
                        $goodsDatas['sold'] = 0;
                        $goodsDatas['time'] = time();
                        $specsName = GoodsSpecsName::where('goods_id',$v['gid'])->select('id','name')->get()->toArray();
                        if ( $specsName ){
                            $num = count($specsName);
                            foreach ( $specsName as $key => $value ){
                                $value = GoodsSpecsVal::where('specs_id',$value['id'])->pluck('val')->toArray();
                                $specsData = getCombinationToString($value,$num);
                            }
                            foreach ( $specsData as $kk => $vv){
                                $specsData[$kk] = array();
                                $specsData[$kk]['specs'] = $vv;
                                $specsData[$kk]['number'] = 0;
                            }
                            $specsName = GoodsSpecsName::where('goods_id',$v['gid'])->get()->toArray();
                            foreach ( $specsData as $key => $value ){
                                $arr = array();
                                $arr = explode('_',$value['specs']);
                                $specsList = '';
                                for ($i = 0;$i<count($specsName);$i++){
                                    $specsList .= $specsName[$i]['name'].':'.$arr[$i].';';
                                }
                                $specs[$key] ='['.$specsList.']--'.$value['number'];
                            }
                            $specsTxt = implode('|',$specs);
                            $goodsDatas['specs_txt'] = $specsTxt;
                        } else {
                            $goodsDatas['specs_txt'] = null;
                        }
                        $storeGoodsDataAdd = $StoresCenterGoodsModel->insert( $goodsDatas );
                    }
                }
                $rico = StoresCenterGoods::where( [ 'stores_id' => $stores_id ] )->select( 'id', 'goodsname', 'inventory', 'sold', 'specs_txt' )->get()->toArray();
                foreach ( $rico as $k => $v ){
                    if ( !is_null($v['specs_txt']) ){
                        $specs = explode('|',$v['specs_txt']);
                        foreach ( $specs as $key => $value ) {
                            $str = substr($value, 0, strrpos($value, "--"));
                            $str = substr($str, 1, -1);
                            $specs[$key] = array_filter(explode(';', $str));
                            foreach ( $specs[$key] as $kk => $vv ){
                                $array[$k][$key]['specs'][$kk] =  substr($vv,strripos($vv,":")+1);
                            }
                            $array[$k][$key]['revise'] = 0;
                            //数量
                            $str2 = strstr($value,'--');
                            $number = substr($str2,2);
                            $array[$k][$key]['number'] = $number;
                        }
                        $specs = $array[$k];
                        $rico[$k]['specs_txt'] = $specs;
                    } else {
                        $rico[$k]['revise'] = 0;
                    }
                }
                $StoresMoney = $StoresCenterModel->where( [ 'id' => $stores_id ] )->value( 'earnest_money' );
                if($rico){
                    return ['code' => 1, 'data' => $rico ,'earnest_money' => $StoresMoney];
                } else {
                    return ['code' => 0, 'data' => '返回门店库存失败'];
                }
                break;
             case 'storeGoodsSet':
                $stores_id = $data['stores_id'];
                $storeData = StoresCenter::where( [ 'id' => $stores_id ] )->select( 'shop_name', 'number','earnest_money')->first();
                $storeGoodsData = $data['storegoods'];
                $priceTotal = 0;
                foreach ($storeGoodsData as $key => $value) {
                    if (!is_null($storeGoodsData[$key]['specs_txt'])) {
                        $oldSpecs = $value['specs_txt'];
                        $gid = StoresCenterGoods::where('id',$value['id'])->value('gid');
                        $specsName = GoodsSpecsName::where('goods_id',$gid)->pluck('name')->toArray();
                        foreach ($oldSpecs as $k => $v) {
                            $specsList = '';
                            for( $i = 0;$i < count($v['specs']);$i++ ){
                                $specsList .= $specsName[$i].':'.$v['specs'][$i].';';
                        }
                        $oldSpecs[$k] = '['.$specsList.']--' . $v['number'];
                        }
                        $storeGoodsData[$key]['specs_before'] = implode('|',$oldSpecs);
                        $revise = 0;
                        foreach ($value['specs_txt'] as $k => $v) {
                            //增加总量
                            $revise += $v['revise'];
                            $specsList = '';
                            if ( $v['number'] + $v['revise'] < 0 ){
                                return ['code' => 0,'data' => '减少数量不能超过库存数量'];
                            }
                            for( $i = 0;$i < count($v['specs']);$i++ ){
                                $specsList .= $specsName[$i].':'.$v['specs'][$i].';';
                        }
                        $value['specs_txt'][$k] = '['.$specsList.']--' . ($v['number'] + $v['revise']);
                    }
                        $storeGoodsData[$key]['specs_txt'] = implode('|', $value['specs_txt']);
                        $storeGoodsData[$key]['inventory'] = $value['inventory'] + $revise;
                    } else {
                        $storeGoodsData[$key]['specs_before'] = null;
                        $storeGoodsData[$key]['inventory'] = $value['inventory'] + $value['revise'];
                    }
                    //判断商品总价是否超过门店订金
                    $goodsId = StoresCenterGoods::where('id', $value['id'])->value('gid');
                    $price = ShopGoods::where('id', $goodsId)->value('memberprice');
                    //库存商品总价
                    $priceTotal += $price * $storeGoodsData[$key]['inventory'];
                    if ( $storeGoodsData[$key]['inventory'] < 0 ){
                        return ['code' => 0 ,'data' => '减少数量不能超过库存数量'];
                    }
                }
                if ($priceTotal > $data['earnest_money']) {
                    return ['code' => 0, 'data' => '库存商品总金额不能超过门店订金'];
                }
                DB::beginTransaction(); //开启事务
                foreach ( $storeGoodsData as $key => $value ){
                    $storeGoodsInventoryData = StoresCenterGoods::where(['stores_id' => $stores_id, 'id' => $value['id']])->value('inventory');
                    StoresCenterGoods::where( [ 'stores_id' => $stores_id, 'id' => $value['id'] ] )
                                        ->update( [ 'inventory' => $value['inventory'], 'specs_txt' => $value['specs_txt'] ] );
                    if ( $storeGoodsInventoryData  != $value['inventory'] ) {
                        $storeGoodsData['store_number'] = $storeData['number'];
                        $storeGoodsData['specs_before'] = $value['specs_before'];
                        $storeGoodsData['specs_after'] = $value['specs_txt'];
                        $storeGoodsData['store_name'] = $storeData['shop_name'];
                        $storeGoodsData['goods_name'] = $value['goodsname'];
                        $storeGoodsData['goods_before'] = $storeGoodsInventoryData;
                        $storeGoodsData['goods_after'] = $value['inventory'];
                        $storeGoodsData['operator'] = Auth::user()->name;
                        $storeGoodsData['addtime'] = time();
                        StoreGoodsSet::create($storeGoodsData);                    
                    }                    
                }
                $res = StoresCenter::where([ 'id' => $stores_id ])->update(['earnest_money' => $data['earnest_money']]);
                if ( !$res  ){
                    DB::rollback();  //回滚
                    return ['code' => 0 ,'data' => '修改失败'];
                } else {
                    DB::commit();  //提交
                return ['code' => 1, 'data' => '' ];
            }
                break; 
            case 'storeSaveAct':
                $rechargeModel = new StoreGoodsSet();
                //关键字
                $keyword = empty($data['keyword'])?0:$data['keyword'];
                $rechargeData = $rechargeModel->orderBy('addtime','desc')->paginate(15);
                //时间
                if(!empty($keyword['addtime'])){
                    $keyword['addtime'][0] = strtotime($keyword['addtime'][0]);
                    $keyword['addtime'][1] = strtotime($keyword['addtime'][1]);
                    $rechargeData =  $rechargeData->where('addtime','>',$keyword['addtime'][0])->where('addtime','<',$keyword['addtime'][1]);
                }
                //关键字
                if(!empty($keyword['keyword'])){
                    $rechargeData =  $rechargeData->where('store_number','like','%'.$keyword['keyword'].'%')
                                    ->orWhere('store_name','like','%'.$keyword['keyword'].'%')
                                    ->orWhere('goods_name','like','%'.$keyword['keyword'].'%');
                }
                foreach ($rechargeData as $k => $v) {
                    $rechargeData[$k]['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
                    if ( !is_null($v['specs_before'])){
                        $rechargeData[$k]['specs_before'] = explode('|',$v['specs_before']);
                        $specsBeforeData = $rechargeData[$k]['specs_before'];
                        foreach ( $specsBeforeData as $key => $value ){
                            $str = substr($value, 0, strrpos($value, "--"));
                            $str = substr($str, 1, -1);
                            $specs[$key] = array_filter(explode(';', $str));
                            foreach ( $specs[$key] as $kk => $vv ){
                                $array[$k][$key]['specs'][] =  substr($vv,strripos($vv,":")+1);
                            }
                              //数量
                              $str2 = strstr($value,'--');
                              $number = substr($str2,2);
                              $array[$k][$key]['number'] = $number;
                        }
                        $specsBeforeData = $array[$k];
                        $rechargeData[$k]['specs_before'] = $specsBeforeData;
                        $rechargeData[$k]['specs_after'] = explode('|',$v['specs_after']);
                        $specsAfterData = $rechargeData[$k]['specs_after'];
                        foreach ( $specsAfterData as $key => $value ){
                            $str = substr($value, 0, strrpos($value, "--"));
                            $str = substr($str, 1, -1);
                            $str = array_filter(explode(';', $str));
                            foreach ( $str as $kk => $vv ){
                                $array[$k][$key]['specs'][$kk] =  substr($vv,strripos($vv,":")+1);
                            }
                            //数量
                            $str2 = strstr($value,'--');
                            $number = substr($str2,2);
                            $array[$k][$key]['number'] = $number;
                            $specsAfterData[$key] = $array[$k][$key];
                        }
                        $rechargeData[$k]['specs_after'] = $specsAfterData;
                    } else {
                        $rechargeData[$k]['specs_after'] = null;
                        $rechargeData[$k]['specs_before'] = null;
                    }
                }
                if ($rechargeData) {
                    return ['code' => 1, 'data' => $rechargeData];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
                break;  
            case 'select_store_record': //查看门店收益记录  
                $keyword = empty($data['keyword'])?"":$data['keyword'];
                $rico = $StoresProfitRecordModel->get_record( $keyword );
                
                foreach ($rico['record'] as $k => $v) {
            
                    switch ( $v['profit_type'] ) {
                       case 1:
                           $v['profit_type'] = '终身门店身份收益';
                           break;
                        case 2:
                           $v['profit_type'] = '消费门店身份收益';
                           break;
                       default:
                           $v['profit_type'] = '';
                           break;
                    }
                    
                    
                    switch ( $v['consum_type'] ) {
                       case 1:
                           $v['consum_type'] = '老会员绑定门店报单';
                           break;
                        case 2:
                           $v['consum_type'] = '老会员绑定门店复销';
                           break;
                        case 3:
                           $v['consum_type'] = '并未绑定门店';
                           break;
                       default:
                           $v['consum_type'] = '';
                           break;
                   }
                }
                if( $rico ){
                    return ['code' => 1, 'data' => $rico ];
                } else {
                    return ['code' => 0, 'data' => '返回门店收益数据失败'];
                }
                break;
        }
    }


    /*
    * 导出门店数据
    */
    public function exportStore(Request $request)
    {
        $StoresCenterModel = new StoresCenter;
        $info['keyword'] = $request->all();
        //检测是否有值
        $info['keyword'] = empty($info['keyword'])?"":$info['keyword'];
        $newData[] = ['会员姓名','门店名称','门店编号','申请人','联系电话','省','市','区','详细地址','经纬度', '评分', '申请时间','门店状态','审核时间'];
        //门店状态
        if( $info['keyword']['type'] != "" ){
            $data = $StoresCenterModel->where('type',$info['keyword']['type']);
        }
        //关键字
        if( !empty( $info['keyword']['keyword'] ) ){
            $data =  $data->where('shop_name','like','%'.$info['keyword']['keyword'].'%')
                ->orWhere('number','like','%'.$info['keyword']['keyword'].'%')
                ->orWhere('name','like','%'.$info['keyword']['keyword'].'%')
                ->orWhere('phone','like','%'.$info['keyword']['keyword'].'%');
        }
        if( $info['keyword']['type'] != "" || !empty( $info['keyword']['keyword'] ) ){
            $data = $data->orderBy('id','desc')->get()->toArray();
        } else {
            $data = $StoresCenterModel->orderBy('id','desc')->get()->toArray();
        }
        foreach ($data as $k=>$v){
            $data[$k]['uid'] = Members::where( 'uid', $v['uid'] )->value('user_name');
        }
        foreach ($data as $key=>$val){
            $val['apply_time']  = date('Y-m-d H:i:s',$val['apply_time']);
            if ( $val['audit_time'] != 0 ) {
                $val['audit_time']  = date('Y-m-d H:i:s',$val['audit_time']);
            }
            switch ( $val['type'] ) {
                case 0:
                    $val['type'] = "待审核";
                    break;
                case 1:
                    $val['type'] = "已通过";
                    break;
                case 2:
                    $val['type'] = "已驳回";
                    break;
                case 3:
                    $val['type'] = "已回收";
                    break;
                case -1:
                    $val['type'] = "已删除";
                    break;  
            }    
            $newData[] = [
                $val['uid'],
                $val['shop_name'],
                $val['number'],
                $val['name'],
                $val['phone'], 
                $val['province'],
                $val['city'], 
                $val['district'],
                $val['address'],
                $val['latitude'],
                $val['score'],
                $val['apply_time'],
                $val['type'],
                $val['audit_time']
            ];
        }
        $dataTime = date('Y-m-d');
        Excel::create("门店列表".$dataTime,function ($excel) use ( $newData){
            $excel->sheet('score',function ($sheet) use ( $newData) {
                $sheet->rows( $newData);
            });
        })->export('xls');
    }


     /*
    * 导出门店收益数据
    */
    public function exportRecord(Request $request)
    {
        $StoresProfitRecordModel = new StoresProfitRecord;
        $info['keyword'] = $request->all();
        //检测是否有值
        $info['keyword'] = empty($info['keyword'])?"":$info['keyword'];

        $newData[] = ['门店编号', '消费订单号', '消费类型', '门店收益类型', '返币金额(奖励币)','来源说明','收益时间'];

        $data =  $StoresProfitRecordModel;

        //关键字
        if( !empty( $info['keyword']['keywords'] ) ){
            $data = $data->where('store_number','like','%'.$info['keyword']['keywords'].'%')->orWhere('ordersn','like','%'.$info['keyword']['keywords'].'%');
        }

         //消费类型
        if(!empty($info['keyword']['consum_type'])){
            $data = $data->where(['consum_type' => $info['keyword']['consum_type'] ]);
        }
      
        //门店收益类型
        if(isset($info['keyword']['profit_type'])){
            $data = $data->where(['profit_type' => $info['keyword']['profit_type'] ]);
        }

        //时间查询
        if( !empty($info['keyword']['addtime'] ) ){
            $data = $data->where('addtime','>',strtotime($info['keyword']['addtime'][0]))->where('addtime','<',strtotime($info['keyword']['addtime'][1]));
        }

        if( $info['keyword']['keywords'] != "" || !empty( $info['keyword']['addtime'] ) || !empty( $info['keyword']['consum_type'] ) || !empty( $info['keyword']['profit_type'] ) ){
            $data = $data->orderBy('id','desc')->get()->toArray();
        } else {
            $data = $StoresProfitRecordModel->orderBy('id','desc')->get()->toArray();
        }
        foreach ($data as $key=>$val){
            $val['addtime']  = date('Y-m-d H:i:s',$val['addtime']);  
            switch ( $val['profit_type'] ) {
               case 1:
                   $val['profit_type'] = '终身门店身份收益';
                   break;
                case 2:
                   $val['profit_type'] = '消费门店身份收益';
                   break;
               default:
                   $val['profit_type'] = '';
                   break;
            }
                           
            switch ( $val['consum_type'] ) {
               case 1:
                   $val['consum_type'] = '老会员绑定门店报单';
                   break;
                case 2:
                   $val['consum_type'] = '老会员绑定门店复销';
                   break;
                case 3:
                   $val['consum_type'] = '并未绑定门店';
                   break;
               default:
                   $val['consum_type'] = '';
                   break;
           }
            $newData[] = [
                $val['store_number'],
                $val['ordersn'],
                $val['consum_type'],
                $val['profit_type'],
                $val['currency'],
                $val['source'],
                $val['addtime'] 
            ];
        }
        $dataTime = date('Y-m-d');
        Excel::create("门店收益列表".$dataTime,function ($excel) use ( $newData){
            $excel->sheet('score',function ($sheet) use ( $newData) {
                $sheet->rows( $newData);
            });
        })->export('xls');
    }
    
        /*
     * 导出门店进货记录
     */
    public function exportPurchase( Request $request )
    {
        $PurchaseModel = new PurchaseOrder();
        $info['keyword'] = $request->all();
        //检测是否有值
        $info['keyword'] = empty($info['keyword'])?"":$info['keyword'];
        $newData[] = ['进货单号','门店名称','门店编号','商品名称','商品单价','商品总数','商品总价','运费','申请人','收货人','收货人电话','收货地址','订单状态','支付时间','发货时间','商品规格'];
        $data = $PurchaseModel->where('status','!=',0)
            ->orderBy('paytime','desc')->get()->toArray();
        //根据支付时间查询
        if (!empty( $info['keyword']['createtime'])) {
            $data = $data->where('paytime', '>=', $info['keyword']['createtime'][0] )
                ->where('paytime', '<=', $info['keyword']['createtime'][1] );

        }
        //关键字
        if( !empty( $info['keyword']['keyword'] ) ){
            $data =  $data->where('stores_name', 'like', '%' . $info['keyword']['keyword'] . '%' )
                ->orWhere( 'stores_num', $info['keyword']['keyword'] )
                ->orWhere( 'ordersn',$info['keyword']['keyword']);
        }
        //订单状态
        if( $info['keyword']['statuse'] != "" ){
            $data = $data->where('status',$info['keyword']['status']);
        }
        foreach ($data as $key => $val) {
            switch ( $val['status'] ) {
                case 1:
                    $val['status'] = "待发货";
                    break;
                case 2:
                    $val['status'] = "已发货";
                    break;
                case 3:
                    $val['status'] = "交易完成";
                    break;
            }
            $newData[] = [
                $val['ordersn'],
                $val['stores_name'],
                $val['stores_num'],
                $val['goods_name'],
                $val['price'],
                $val['total_quantity'],
                $val['total_price'],
                $val['postage'],
                $val['name'],
                $val['consignee'],
                $val['phone'],
                $val['address'],
                $val['status'],
                $val['paytime'],
                $val['express_time'],
                $val['specs_txt'],
            ];
        }
        $dataTime = date('Y-m-d');
        Excel::create("门店进货记录列表".$dataTime,function ($excel) use ( $newData){
            $excel->sheet('paytime',function ($sheet) use ( $newData) {
                $sheet->rows( $newData);
            });
        })->export('xls');


    }


    /*
     * 导出门店补货记录
     */
    public function exportReplenish( Request $request )
    {
        $ReplenishModel = new Replenish();
        $info['keyword'] = $request->all();
        //检测是否有值
        $info['keyword'] = empty($info['keyword'])?"":$info['keyword'];
        $newData[] = ['补货单号','门店名称','门店编号','商品名称','报单数量','报单规格','复销数量','复销规格','运费','申请人','收货人','收货人电话','收货地址','订单状态','支付时间','发货时间'];
        $data = $ReplenishModel->where('status','!=',0)
            ->orderBy('paytime','desc')->get()->toArray();
        //根据支付时间查询
        if (!empty( $info['keyword']['createtime'])) {
            $data = $data->where('paytime', '>=', $info['keyword']['createtime'][0] )
                ->where('paytime', '<=', $info['keyword']['createtime'][1] );
        }
        //关键字
        if( !empty( $info['keyword']['keyword'] ) ){
            $data =  $data->where('stores_name', 'like', '%' . $info['keyword']['keyword'] . '%' )
                ->orWhere( 'stores_num', $info['keyword']['keyword'] )
                ->orWhere( 'ordersn',$info['keyword']['keyword']);
        }
        //订单状态
        if( $info['keyword']['statuse'] != "" ){
            $data = $data->where('status',$info['keyword']['status']);
        }
        foreach ($data as $key => $val) {
            switch ( $val['status'] ) {
                case 1:
                    $val['status'] = "待发货";
                    break;
                case 2:
                    $val['status'] = "已发货";
                    break;
                case 3:
                    $val['status'] = "交易完成";
                    break;
            }
            $newData[] = [
                $val['ordersn'],
                $val['stores_name'],
                $val['stores_num'],
                $val['goods_name'],
                $val['invoices'],
                $val['invoices_specs'],
                $val['resale'],
                $val['resale_specs'],
                $val['postage'],
                $val['name'],
                $val['consignee'],
                $val['phone'],
                $val['address'],
                $val['status'],
                $val['paytime'],
                $val['express_time']
            ];
        }
        $dataTime = date('Y-m-d');
        Excel::create("门店补货记录列表".$dataTime,function ($excel) use ( $newData){
            $excel->sheet('paytime',function ($sheet) use ( $newData) {
                $sheet->rows( $newData);
            });
        })->export('xls');

    }


}